package org.deadline.model.user;

import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Iterator;
import java.util.List;
import java.util.Random;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;

import org.deadline.model.config.EnumerationDataOnDemand;
import org.deadline.model.config.Guid;
import org.deadline.model.config.LdapServer;
import org.deadline.model.config.LdapServerDataOnDemand;
import org.deadline.repository.user.PersonRepository;
import org.deadline.service.user.PersonService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.stereotype.Component;

@Configurable
@Component
public class PersonDataOnDemand {

	private Random rnd = new SecureRandom();

	private List<Person> data;
	
	@Autowired
    private EnumerationDataOnDemand enumerationDataOnDemand;

	@Autowired
    private LdapServerDataOnDemand ldapServerDataOnDemand;

	@Autowired
    private PersonFilterDataOnDemand personFilterDataOnDemand;

	@Autowired
    PersonService personService;

	@Autowired
    PersonRepository personRepository;

	public Person getNewTransientPerson(int index) {
        Person obj = new Person();
        setGuid(obj, index);
        setCreatedBy(obj, index);
        setCreationDate(obj, index);
        setDateOfBirth(obj, index);
        setDeleted(obj, index);
        setDisplayName(obj, index);
        setFirstName(obj, index);
        setJobDescription(obj, index);
        setLastName(obj, index);
        setLdapServer(obj, index);
        setMiddleName(obj, index);
        setModificationDate(obj, index);
        setNamePrefix(obj, index);
        setPassword(obj, index);        
        setSalt(obj, index);
        setUserName(obj, index);
        return obj;
    }

	public void setGuid(Person obj, int index) {
        Guid embeddedClass = new Guid();
        setGuidTenentId(embeddedClass, index);
        setGuidUuid(embeddedClass, index);
        obj.setGuid(embeddedClass);
    }

	public void setGuidTenentId(Guid obj, int index) {
        String tenentId = "tenentId_" + index;
        if (tenentId.length() > 100) {
            tenentId = tenentId.substring(0, 100);
        }
        obj.setTenentId(tenentId);
    }

	public void setGuidUuid(Guid obj, int index) {
        String uuid = "uuidxxxxxxxxxxxxxxxxxxxxxxxxxx_" + index;
        if (uuid.length() > 32) {
            uuid = uuid.substring(0, 32);
        }
        obj.setUuid(uuid);
    }

	public void setCreatedBy(Person obj, int index) {
        Person createdBy = obj;
        obj.setCreatedBy(createdBy);
    }

	public void setCreationDate(Person obj, int index) {
        Date creationDate = new GregorianCalendar(Calendar.getInstance().get(Calendar.YEAR), Calendar.getInstance().get(Calendar.MONTH), Calendar.getInstance().get(Calendar.DAY_OF_MONTH), Calendar.getInstance().get(Calendar.HOUR_OF_DAY), Calendar.getInstance().get(Calendar.MINUTE), Calendar.getInstance().get(Calendar.SECOND) + new Double(Math.random() * 1000).intValue()).getTime();
        obj.setCreationDate(creationDate);
    }

	public void setDateOfBirth(Person obj, int index) {
        Date dateOfBirth = new GregorianCalendar(Calendar.getInstance().get(Calendar.YEAR), Calendar.getInstance().get(Calendar.MONTH), Calendar.getInstance().get(Calendar.DAY_OF_MONTH), Calendar.getInstance().get(Calendar.HOUR_OF_DAY), Calendar.getInstance().get(Calendar.MINUTE), Calendar.getInstance().get(Calendar.SECOND) + new Double(Math.random() * 1000).intValue()).getTime();
        obj.setDateOfBirth(dateOfBirth);
    }

	public void setDeleted(Person obj, int index) {
        Boolean deleted = true;
        obj.setDeleted(deleted);
    }

	public void setDisplayName(Person obj, int index) {
        String displayName = "displayName_" + index;
        if (displayName.length() > 255) {
            displayName = displayName.substring(0, 255);
        }
        obj.setDisplayName(displayName);
    }

	public void setFirstName(Person obj, int index) {
        String firstName = "firstName_" + index;
        if (firstName.length() > 100) {
            firstName = firstName.substring(0, 100);
        }
        obj.setFirstName(firstName);
    }

	public void setJobDescription(Person obj, int index) {
        String jobDescription = "jobDescription_" + index;
        if (jobDescription.length() > 100) {
            jobDescription = jobDescription.substring(0, 100);
        }
        obj.setJobDescription(jobDescription);
    }

	
	public void setLastName(Person obj, int index) {
        String lastName = "lastName_" + index;
        if (lastName.length() > 100) {
            lastName = lastName.substring(0, 100);
        }
        obj.setLastName(lastName);
    }

	public void setLdapServer(Person obj, int index) {
        LdapServer ldapServer = ldapServerDataOnDemand.getRandomLdapServer();
        obj.setLdapServer(ldapServer);
    }

	public void setMiddleName(Person obj, int index) {
        String middleName = "middleName_" + index;
        if (middleName.length() > 100) {
            middleName = middleName.substring(0, 100);
        }
        obj.setMiddleName(middleName);
    }

	public void setModificationDate(Person obj, int index) {
        Date modificationDate = new GregorianCalendar(Calendar.getInstance().get(Calendar.YEAR), Calendar.getInstance().get(Calendar.MONTH), Calendar.getInstance().get(Calendar.DAY_OF_MONTH), Calendar.getInstance().get(Calendar.HOUR_OF_DAY), Calendar.getInstance().get(Calendar.MINUTE), Calendar.getInstance().get(Calendar.SECOND) + new Double(Math.random() * 1000).intValue()).getTime();
        obj.setModificationDate(modificationDate);
    }

	public void setNamePrefix(Person obj, int index) {
        String namePrefix = "namePrefix_" + index;
        if (namePrefix.length() > 20) {
            namePrefix = namePrefix.substring(0, 20);
        }
        obj.setNamePrefix(namePrefix);
    }

	public void setPassword(Person obj, int index) {
        String password = "password_" + index;
        if (password.length() > 255) {
            password = password.substring(0, 255);
        }
        obj.setPassword(password);
    }

	
	public void setSalt(Person obj, int index) {
        String salt = "salt_" + index;
        if (salt.length() > 255) {
            salt = salt.substring(0, 255);
        }
        obj.setSalt(salt);
    }

	
	public void setUserName(Person obj, int index) {
        String userName = "userName_" + index;
        if (userName.length() > 255) {
            userName = userName.substring(0, 255);
        }
        obj.setUserName(userName);
    }

	public Person getSpecificPerson(int index) {
        init();
        if (index < 0) {
            index = 0;
        }
        if (index > (data.size() - 1)) {
            index = data.size() - 1;
        }
        Person obj = data.get(index);
        Long id = obj.getId();
        return personService.findPerson(id);
    }

	public Person getRandomPerson() {
        init();
        Person obj = data.get(rnd.nextInt(data.size()));
        Long id = obj.getId();
        return personService.findPerson(id);
    }

	public boolean modifyPerson(Person obj) {
        return false;
    }

	public void init() {
        int from = 0;
        int to = 10;
        data = personService.findPersonEntries(from, to);
        if (data == null) {
            throw new IllegalStateException("Find entries implementation for 'Person' illegally returned null");
        }
        if (!data.isEmpty()) {
            return;
        }
        
        data = new ArrayList<Person>();
        for (int i = 0; i < 10; i++) {
            Person obj = getNewTransientPerson(i);
            try {
                personService.savePerson(obj);
            } catch (ConstraintViolationException e) {
                StringBuilder msg = new StringBuilder();
                for (Iterator<ConstraintViolation<?>> iter = e.getConstraintViolations().iterator(); iter.hasNext();) {
                    ConstraintViolation<?> cv = iter.next();
                    msg.append("[").append(cv.getConstraintDescriptor()).append(":").append(cv.getMessage()).append("=").append(cv.getInvalidValue()).append("]");
                }
                throw new RuntimeException(msg.toString(), e);
            }
            personRepository.flush();
            data.add(obj);
        }
    }
}
